package com.iscreen.core.services.parameters;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.ejb3.annotation.RemoteBinding;

import com.iscreen.entities.SystemParameters;
import com.iscreen.entities.SystemParametersPK;
import com.iscreen.utils.exceptions.IScreenException;
import com.iscreen.utils.exceptions.IScreenExceptionCodes;

/**
 * Session Bean implementation class ParametersHandlerBean
 */
@Stateless
@RemoteBinding(jndiBinding="ParametersHandler")
public class ParametersHandlerBean implements ParametersHandler {

	@PersistenceContext
	private EntityManager em;
	
	
    /**
     * Default constructor. 
     */
    public ParametersHandlerBean() {
        // TODO Auto-generated constructor stub
    }

	public String getParameterValue(String section, String parameterName) throws IScreenException
	{
		SystemParameters parameter = getSystemParameter(section, parameterName);
		if (parameter == null || parameter.getParamValue() == null || parameter.getParamValue().isEmpty())
		{
			throw new IScreenException(IScreenExceptionCodes.SYSTEM_PARAMETER_NOT_FOUND, "System parameter not found. Section: " + section + ". Name: " + parameterName);
		}
		return parameter.getParamValue();
	}

	public String getParameterValue(String section, String parameterName, String defaultValue)
	{
		SystemParameters parameter = getSystemParameter(section, parameterName);
		if (parameter == null || parameter.getParamValue() == null || parameter.getParamValue().isEmpty())
		{
			return defaultValue;
		}
		return parameter.getParamValue();
	}
	
	public void updateParameterValue(String section, String parameterName, String value) throws IScreenException
	{
		SystemParameters parameter = getSystemParameter(section, parameterName);
		if (parameter == null)
		{
			throw new IScreenException(IScreenExceptionCodes.SYSTEM_PARAMETER_NOT_FOUND, "System parameter not found. Section: " + section + ". Name: " + parameterName);
		}
		parameter.setParamValue(value);
		em.persist(parameter);
	}
	
	private SystemParameters getSystemParameter(String section,
			String parameterName)
	{
		SystemParametersPK pk = getSystemParameterPK(section, parameterName);
		SystemParameters parameter = em.find(SystemParameters.class, pk);
		return parameter;
	}

	private SystemParametersPK getSystemParameterPK(String section, String parameterName)
	{
		SystemParametersPK pk = new SystemParametersPK();
		pk.setParamName(parameterName);
		pk.setSection(section);
		return pk;
	}
    
}
